import {time, offset, manyTapInterval} from './config'

const tapCount = 2

export default {
  bind(el, binding) {
    const stop = binding.modifiers.stop || false
    const prevent = binding.modifiers.prevent || false
    const callback = binding.value
    let timer = null
    let double = null
    let Event = {
      el
    }
    let moveCount = 0
    let count = 0
    let status = false
    el.addEventListener('touchstart', function(event){

      if(event.changedTouches.length > 1){
        status = false
        return
      }

      moveCount = 0
      status = true

      timer = setTimeout(() => {

        if(!status)
          return

        clearTimeout(double)
        double = null
        timer = null
        status = false

      }, time)

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchmove', function(event){

      if(event.changedTouches.length > 1){
        status = false
        return
      }

      if(!status)
        return

      moveCount += 1
      if(moveCount > offset){
        clearTimeout(double)
        clearTimeout(timer)
        double = null
        timer = null
        status = false
        count = 0
      }

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchend', function(event) {

      if(!status)
        return

      clearTimeout(timer)
      timer = null

      count += 1

      if(count < tapCount){
        return double = setTimeout(() => {
          status = false
          double = null
          count = 0
        }, manyTapInterval)
      }

      clearTimeout(double)
      double = null
      count = 0

      Event.type = 'double'
      Event.e = event

      callback(Object.assign({}, Event))

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchleave', function(event){

      if(!status)
        return

      clearTimeout(double)
      clearTimeout(timer)
      double = null
      timer = null
      status = false
      count = 0

      if(prevent)
        event.preventDefault()

    }, false)

    el.addEventListener('touchcancel', function(event){


      if(!status)
        return

      clearTimeout(double)
      clearTimeout(timer)
      double = null
      timer = null
      count = 0

      if(stop)
        event.stopPropagation()
      if(prevent)
        event.preventDefault()

    }, false)
  }
}
